﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DistributedLocking;
using Volo.Abp.Domain.Repositories;

namespace Himp.Platform.Dc
{
    public class BizSeqService : DcAppService, IBizSeqService
    {
        private readonly IRepository<BizSeq, Guid> _bizSeqRepository;
        private readonly IAbpDistributedLock _distributedLock;

        public BizSeqService(IRepository<BizSeq, Guid> bizSeqRepository
            , IAbpDistributedLock distributedLock)
        {
            _bizSeqRepository = bizSeqRepository;
            _distributedLock = distributedLock;
        }

        public async Task<string> GetAsync(string type)
        {
            var iQuery = await _bizSeqRepository.GetQueryableAsync();

            if (iQuery.Count(b => b.BizSeqType == type) == 0)
            {
                await _bizSeqRepository.InsertAsync(
                    new BizSeq()
                    {
                        BizSeqType = type,
                        Format = "{0:00000000}",
                        CurrSeq = 0,
                    }, autoSave: true);
            }

            await using (var handle = await _distributedLock.TryAcquireAsync(type.ToString()))
            {
                if (handle != null)
                {
                    var businessSerialNumber = await _bizSeqRepository.GetAsync(b => b.BizSeqType == type);
                    businessSerialNumber.CurrSeq++;
                    return string.Format(businessSerialNumber.Format, businessSerialNumber.CurrSeq);
                }
            }

            return Guid.NewGuid().ToString("N");
        }
    }
}
